<template>
  <CustomDialog v-model:visible="dialogVisible" top="8vh" curent-class="member-dialog">
    <div class="member-container">
      <div class="title">会员</div>
      <div class="vip-box">
        <div class="vip-box-left" v-loading="searchLoading">
          <div class="desc-info-box">
            <div class="title-box">
              <div class="title-box-left">
                <img class="image" src="@/assets/images/home/vip-info-icon.png" alt="" />
                <div class="title-box-left-desc">
                  <div class="name">
                    <span v-if="memberDetail">{{
                      memberDetail.real_name || memberDetail.nick_name
                    }}</span>
                    <span v-else>会员名称</span>
                  </div>
                  <div class="level" v-if="memberDetail && memberDetail.grade">
                    {{ memberDetail.grade.name }}
                  </div>
                </div>
              </div>
              <div class="title-box-right">
                <span v-if="memberDetail && memberDetail.user_id">{{
                  hiddenPhone(memberDetail.user_id)
                }}</span>
                <span v-else>会员卡号</span>
              </div>
            </div>
            <div class="phone">
              联系电话<span v-if="memberDetail && memberDetail.mobile"
                >：{{ hiddenPhone(memberDetail.mobile) }}</span
              >
            </div>
            <div class="birthday">
              生日<span v-if="memberDetail && memberDetail.birthday"
                >：{{ memberDetail.birthday }}</span
              >
            </div>
            <!-- 余额 / 积分 -->
            <div class="balanceAndIntegral-box" v-if="memberDetail">
              <div class="balance">
                <div class="desc">余额</div>
                <div class="money">￥{{ memberBalanceMoney }}</div>
              </div>
              <div class="integral">
                <div class="desc">积分</div>
                <div class="count">{{ memberDetail.points ?? 0 }}</div>
              </div>
            </div>
            <div class="balanceAndIntegral-box-notvip" v-else>
              <span>余额</span>
              <span>积分</span>
            </div>
            <!-- 挂失状态角标 -->
            <div class="loss-img-box" v-if="memberDetail && memberDetail.status == 0">
              <img src="@/assets/images/vipMember/loss.png" alt="" />
            </div>
          </div>
          <div class="vip-button-box">
            <div class="vip-button-box-left">
              <el-button
                class="cancal-money-btn"
                @click="handleToggleVipDiscount"
                :loading="discountLoading"
              >
                <span v-if="isVipDiscountOn">撤销会员折扣</span>
                <span v-else>开启会员折扣</span>
              </el-button>
              <el-button
                class="cancal-money-btn"
                @click="handleUnbindMember"
                :loading="submitLoading"
                :disabled="!hasMember"
              >
                <span>撤销会员</span>
              </el-button>
            </div>
            <el-button class="recharge-btn" @click="handleOpenRecharge">充值</el-button>
          </div>
        </div>
        <div class="vip-box-right">
          <div class="search-input-box">
            <div class="input-box">
              <input
                class="input"
                v-model.trim="dialogKeyword"
                type="text"
                placeholder="请输入会员信息进行查询"
                @keyup.enter="handleSearchMemberDetail"
              />
              <img
                class="image"
                src="@/assets/images/home/input-clear.png"
                alt="清空"
                v-if="dialogKeyword"
                @click="handleClearInput"
              />
            </div>
            <el-button
              class="search-btn"
              :style="{ background: dialogKeyword ? '#7c0a03' : '#d2d2d2' }"
              @click="handleSearchMemberDetail"
              :loading="searchLoading"
            >
              查询
            </el-button>
          </div>
          <NumberKeyboard
            v-model:keyword="dialogKeyword"
            v-model:loading="submitLoading"
            @onInputKeyboard="onInputKeyboard"
            @onCancel="handleClearInput"
            @onConfirm="handleKeyboardConfirm"
          />
        </div>
      </div>
    </div>
  </CustomDialog>

  <!-- 充值弹窗 -->
  <RechargeBalanceDialog
    v-model:visible="showRechargeDialog"
    :memberId="memberDetail?.user_id"
    @onSuccess="handleRechargeSuccess"
  />
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'
import RechargeBalanceDialog from '@/views/Member/components/RechargeBalanceDialog.vue'
import { deskOrderBindUser, editMemberDiscount } from '@/api/desktop'
import { searchMemberDetail } from '@/api/member'

interface Props {
  modelValue: boolean
  deskDetail?: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  deskDetail: null
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

const dialogKeyword = ref('')
const memberDetail = ref<any | null>(null)
const submitLoading = ref(false)
const memberLoading = ref(false)
const searchLoading = ref(false)
const discountLoading = ref(false)

// 充值弹窗状态
const showRechargeDialog = ref(false)

const hasMember = computed(
  () => !!(props.deskDetail?.user && (props.deskDetail.user.id || props.deskDetail.user.grade))
)
const isVipDiscountOn = computed(() => {
  return props.deskDetail?.member_discount < 10 ? true : false
})

watch(
  () => props.modelValue,
  val => {
    if (val) {
      // 打开弹框时，若已绑定，做回显（此处仅展示 deskDetail.user 简要信息）
      memberDetail.value = props.deskDetail?.user || null
      dialogKeyword.value = ''
    } else {
      dialogKeyword.value = ''
      memberDetail.value = null
    }

    console.log('hasMember:>>>', hasMember.value)
  }
)

const hiddenPhone = (val: string | number) => {
  const s = String(val)
  if (s.length < 7) return s
  return s.slice(0, 3) + '****' + s.slice(-4)
}

// 余额（余额 + 赠送余额）
const memberBalanceMoney = computed(() => {
  if (!memberDetail.value) return 0
  const balance = Number(memberDetail.value.balance || 0)
  const bonus = Number(memberDetail.value.bonus_balance || 0)
  return (balance + bonus).toFixed(2)
})

const handleClearInput = () => {
  dialogKeyword.value = ''
}

const onInputKeyboard = (val: string) => {
  dialogKeyword.value = val
}

// 搜索会员详情（对接真实接口）
const handleSearchMemberDetail = async () => {
  if (!dialogKeyword.value) {
    ElMessage.warning('请输入会员信息进行查询')
    return
  }
  searchLoading.value = true
  try {
    const res = await searchMemberDetail({ search: dialogKeyword.value })
    if (res.status === 200) {
      const detail = res?.data?.detail
      if (!detail) {
        ElMessage.error('未找到会员信息')
      } else {
        memberDetail.value = detail
      }
    } else {
      ElMessage.error(res.data?.message || '查询失败')
    }
  } finally {
    searchLoading.value = false
  }
}

// 仅绑定所选会员（不做查询/不做解绑）
const handleBindSelectedMember = async () => {
  const recordId = props.deskDetail?.id
  const userId = memberDetail.value?.user_id
  if (!recordId) return
  if (!userId) {
    ElMessage.error('未找到会员信息')
    return
  }
  submitLoading.value = true
  try {
    const res = await deskOrderBindUser({ record_id: recordId, user_id: userId })
    if (res.status === 200) {
      ElMessage.success('绑定会员成功')
      // 默认开启会员价 调用一下
      // handleToggleVipDiscount(true)
      emit('update:modelValue', false)
      emit('success')
    } else {
      ElMessage.error(res.data?.message || '绑定会员失败')
    }
  } catch (e) {
    ElMessage.error('绑定会员失败')
  } finally {
    submitLoading.value = false
  }
}

// 撤销回应
const handleUnbindMember = async () => {
  const recordId = props.deskDetail?.id
  if (!recordId) return
  submitLoading.value = true
  try {
    const res = await deskOrderBindUser({ record_id: recordId, user_id: 0 })
    if (res.status === 200) {
      ElMessage.success('撤销会员成功')
      emit('update:modelValue', false)
      emit('success')
    } else {
      ElMessage.error(res.data?.message || '撤销会员失败')
    }
  } catch (e) {
    ElMessage.error('撤销会员失败')
  } finally {
    submitLoading.value = false
  }
}

// 键盘确认：直接按当前回显会员进行绑定
const handleKeyboardConfirm = async () => {
  if (!memberDetail.value) {
    ElMessage.error('未找到会员信息')
    return
  }
  await handleBindSelectedMember()
}

// 切换会员优惠（开启/撤销）
const handleToggleVipDiscount = async (isBind = false) => {
  if (!props.deskDetail?.id) return
  if (!hasMember.value) {
    ElMessage.warning('请先绑定会员再操作会员优惠')
    return
  }
  discountLoading.value = true
  try {
    let status = isVipDiscountOn.value ? 0 : 1
    const res = await editMemberDiscount({ status, record_id: props.deskDetail.id })
    if (res.status === 200) {
      ElMessage.success(status === 1 ? '开启会员折扣成功' : '撤销会员折扣成功')

      emit('success')
    } else {
      ElMessage.error(res.data?.message || '操作失败')
    }
  } catch (e) {
    console.log(e)
    // ElMessage.error('操作失败', e)
  } finally {
    discountLoading.value = false
  }
}

// 打开充值弹窗
const handleOpenRecharge = () => {
  if (!memberDetail.value?.user_id) {
    ElMessage.warning('请先查询并选择会员')
    return
  }

  // 直接打开充值弹窗
  showRechargeDialog.value = true
}

// 充值成功后的回调
const handleRechargeSuccess = () => {
  showRechargeDialog.value = false
  // 刷新会员信息
  handleSearchMemberDetail()
}

// 绑定或解绑
const handleBindOrUnbind = async () => {
  const recordId = props.deskDetail?.id
  if (!recordId) return
  // 若已有会员，则解绑；否则绑定输入框查到的会员
  const isBind = hasMember.value
  const userId = isBind ? 0 : memberDetail.value?.user_id
  if (!isBind && !userId) {
    ElMessage.warning('请先查询并选择会员')
    return
  }
  submitLoading.value = true
  try {
    const res = await deskOrderBindUser({ record_id: recordId, user_id: userId })
    if (res.status === 200) {
      ElMessage.success(isBind ? '解绑会员成功' : '绑定会员成功')
      emit('update:modelValue', false)
      emit('success')
    } else {
      ElMessage.error(res.data?.message || (isBind ? '解绑会员失败' : '绑定会员失败'))
    }
  } catch (e) {
    ElMessage.error(isBind ? '解绑会员失败' : '绑定会员失败')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.member-container {
  .title {
    padding-left: 20px;
    font-size: 20px;
    font-weight: 700;
    text-align: left;
    color: #353535;
  }
  .vip-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 30px;
    .vip-box-left {
      padding-right: 30px;
      .desc-info-box {
        position: relative;
        width: 420px;
        height: 260px;
        box-sizing: border-box;
        padding: 20px;
        background: url('@/assets/images/vipMember/vip-bgimg.png');
        background-size: cover;
        border-radius: 12px;
        .title-box {
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          .title-box-left {
            display: flex;
            align-items: center;
            .image {
              flex-shrink: 0;
              width: 30px;
              height: 30px;
              margin-right: 10px;
            }
            .title-box-left-desc {
              .name {
                font-size: 18px;
                font-weight: 700;
                color: #ffe2c2;
              }
              .level {
                font-size: 12px;
                color: #b07a4f;
              }
            }
          }
          .title-box-right {
            font-size: 12px;
            color: #a1a1a1;
          }
        }
        .phone {
          font-size: 12px;
          color: #ffe2c2;
          margin-top: 16px;
        }
        .birthday {
          font-size: 12px;
          color: #ffe2c2;
          margin-top: 8px;
        }
        .balanceAndIntegral-box {
          display: flex;
          align-items: center;
          margin-top: 80px;
          .balance {
            color: #ffe2c2;
            text-align: left;
            margin-right: 20px;
            .desc {
              font-size: 10px;
            }
            .money {
              font-size: 16px;
              margin-top: 6px;
            }
          }
          .integral {
            color: #ffe2c2;
            text-align: left;
            margin-right: 20px;
            .desc {
              font-size: 10px;
            }
            .count {
              font-size: 16px;
              margin-top: 6px;
            }
          }
        }
        .balanceAndIntegral-box-notvip {
          display: flex;
          align-items: center;
          gap: 20px;
          margin-top: 20px;
          color: #ffe2c2;
          font-size: 16px;
        }
        .loss-img-box {
          position: absolute;
          bottom: 5px;
          right: 5px;
          img {
            width: 98px;
            height: 92px;
          }
        }
      }
      .vip-button-box {
        margin: 20px 0;
        display: flex;
        flex-direction: column;
        gap: 12px;
        .vip-button-box-left {
          display: flex;
          align-items: center;
        }
        .cancal-money-btn {
          width: 202px;
          height: 52px;
          border-radius: 12px;
          font-size: 18px;
        }
        .recharge-btn {
          width: 420px;
          background: #7c0a03;
          color: #fff;
          height: 52px;
          border-radius: 12px;
          font-size: 18px;
          margin-left: 0px !important;
        }
        .bind-btn {
          width: 420px;
          height: 52px;
          border-radius: 12px;
          font-size: 18px;
        }
      }
    }
    .vip-box-right {
      padding-left: 30px;
      border-left: 1px solid #e2e2e2;
      .search-input-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 80px;
        .input-box {
          width: 384px;
          height: 48px;
          background: #ffffff;
          border: 1px solid #d2d2d2;
          border-radius: 12px;
          box-sizing: border-box;
          padding: 0 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .input {
            width: 300px;
            font-size: 14px;
            color: #333333;
            outline: none;
            border: none;
          }
          .image {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            cursor: pointer;
          }
        }
        .search-btn {
          width: 120px;
          height: 48px;
          line-height: 48px;
          background: #d2d2d2;
          border-radius: 12px;
          font-size: 14px;
          text-align: center;
          color: #ffffff;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
